<template>
<div class="">
  <!-- 面包屑导航区域 -->
  <el-breadcrumb separator-class="el-icon-arrow-right">
    <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>权限管理</el-breadcrumb-item>
    <el-breadcrumb-item>角色列表</el-breadcrumb-item>
  </el-breadcrumb>
  <!-- 卡片视图区域 -->
  <el-card>
    <!-- 添加角色按钮 -->
    <el-row>
      <el-col>
        <el-button type="primary" @click="addRoleDialogVisiable = true">添加角色</el-button>
      </el-col>
    </el-row>
    <!-- 用户列表表格 -->
    <el-table :data="roleList" border stripe>
      <!-- 展开列，显示三个级别的权限标签 -->
      <el-table-column type="expand">
        <template v-slot="scope">
          <!-- 最外层循环-->
          <el-row :class="['bdbottom', index1 === 0 ? 'bdtop' : '', 'flex-center']" v-for="(item1, index1) in scope.row.children" :key="item1.id">
            <!-- 第一列，渲染一级权限标签 -->
            <el-col :span="5">
              <el-tag closable @close="removeRightById(scope.row, item1.id)">{{ item1.authName }}</el-tag>
              <i class="el-icon-caret-right"></i>
            </el-col>
            <!-- 第二列，渲染二、三级权限标签 -->
            <el-col :span="19">
              <!-- 内层循环 -->
              <el-row v-for="(item2, index2) in item1.children" :key="item2.id">
                <!-- 二级权限标签 -->
                <el-col :span="6" :class="[index2 !== 0 ? 'bdtop' : '']">
                  <el-tag type="success" closable @close="removeRightById(scope.row, item2.id)">{{ item2.authName }}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <!-- 三级权限标签 -->
                <el-col :span="18">
                  <el-tag type="info" v-for="item3 in item2.children" :key="item3.id" closable @close="removeRightById(scope.row, item3.id)">{{ item3.authName }}</el-tag>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <!-- 索引列 -->
      <el-table-column type="index" label="序号" width="55" />
      <el-table-column label="角色名称" prop="roleName" />
      <el-table-column label="角色名描述" prop="roleDesc" />
      <el-table-column label="操作">
        <template v-slot="slotProps">
          <el-button type="primary" @click="showEditDialog(slotProps.row)">编辑</el-button>
          <el-button type="danger" @click="deleteRole(slotProps.row)">删除</el-button>
          <el-button type="warning" @click="showSetRightsDialog(slotProps.row)">分配权限</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
  <!-- 分配权限的对话框 -->
  <el-dialog title="提示" :visible.sync="setRightsDialogVisiable" width="50%" @close="setRightDialogClosed">
    <!-- 权限树 -->
    <el-tree ref="rightsTreeRef" :data="rightsTree" :props="treeProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="defaultCheckedKeys">
    </el-tree>
    <span slot="footer">
      <el-button @click="setRightsDialogVisiable = false">取 消</el-button>
      <el-button type="primary" @click="allotRights">确 定</el-button>
    </span>
  </el-dialog>
  <!-- 添加角色的对话框 -->
  <el-dialog title="添加角色" :visible.sync="addRoleDialogVisiable" width="50%" @close="addRoletDialogClosed">
    <el-form :model="addForm" :rules="addFormRules" ref="addFormRef">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="addForm.roleName"></el-input>
      </el-form-item>
      <el-form-item label="角色描述" prop="roleDesc">
        <el-input v-model="addForm.roleDesc"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer">
      <el-button @click="addRoleDialogVisiable = false">取 消</el-button>
      <el-button type="primary" @click="addRole">确 定</el-button>
    </span>
  </el-dialog>
  <!-- 编辑角色描述的对话框 -->
  <el-dialog title="编辑角色描述" :visible.sync="editDescDialogVisiable" width="50%" @close="editDescDialogClosed">
    <el-form :model="editForm" ref="editFormRef">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="editForm.roleName" disabled></el-input>
      </el-form-item>
      <el-form-item label="角色描述" prop="roleDesc">
        <el-input v-model="editForm.roleDesc"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer">
      <el-button @click="editDescDialogVisiable = false">取 消</el-button>
      <el-button type="primary" @click="editDesc">确 定</el-button>
    </span>
  </el-dialog>
</div>
</template>

<script>
export default {
  name: "",
  data() {
    return {
      // 所有的角色
      roleList: [],
      // 控制分配权限对话框的显示与隐藏
      setRightsDialogVisiable: false,
      // 所有的权限，树结构
      rightsTree: [],
      // 树形控件的属性绑定对象，label绑定到rightsTree的authName，children绑定到rightsTree的children
      treeProps: {
        label: "authName",
        children: "children",
      },
      // 默认选中的节点id
      defaultCheckedKeys: [],
      // 当前即将分配权限的角色 id
      roleId: "",
      // 添加角色对话框的显示
      addRoleDialogVisiable: false,
      // 添加角色的表单
      addForm: {
        roleName: "",
        roleDesc: "",
      },
      // 添加角色的表单的验证规则
      addFormRules: {
        roleName: [{
          required: true,
          message: "请输入角色名称",
          trigger: "blur",
        }, ],
      },
      // 编辑角色描述对话框的显示
      editDescDialogVisiable: false,
      editForm: {
        roleName: "",
        roleDesc: "",
      },
    };
  },
  created() {
    // 获取所有角色列表
    this.getRoleList();
  },
  methods: {
    // 获取角色列表
    async getRoleList() {
      const {
        data: res
      } = await this.$request.get("roles");
      if (res.meta.status !== 200) {
        return this.$message.error("服务器错误，获取角色列表失败");
      }
      // 保存角色列表数据
      this.roleList = res.data;
    },
    // 按下权限标签的 x ，取消用户的权限，参数：角色，权限id
    async removeRightById(role, rightId) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该权限, 是否继续?",
        "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);

      if (confirmResult !== "confirm") {
        return this.$message.info("取消了删除");
      }
      // 发起取消权限的请求
      const {
        data: res
      } = await this.$request.delete(
        `roles/${role.id}/rights/${rightId}`
      );
      if (res.meta.status !== 200)
        return this.$message.error("服务器错误，取消权限失败");
      // 保存用户的最新权限
      role.children = res.data;
    },
    // 点击修改权限按钮对话框
    async showSetRightsDialog(role) {
      this.roleId = role.id;
      // 请求权限数
      const {
        data: res
      } = await this.$request("rights/tree");
      if (res.meta.status != 200) {
        return this.$message.error("服务器错误，获取权限列树失败");
      }
      // 保存权限树数据
      this.rightsTree = res.data;
      // 获取该角色的权限的id
      this.getLeafKeys(role, this.defaultCheckedKeys);
      this.setRightsDialogVisiable = true;
    },
    // 递归获取角色下所有三级权限的id，并保存到 arr 数组中
    getLeafKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach((item) => this.getLeafKeys(item, arr));
    },
    // 监听关闭分配权限对话框的关闭世事件，清空权限数组
    setRightDialogClosed() {
      this.defaultCheckedKeys = [];
    },
    // 点击确定按钮，为角色分配权限
    async allotRights() {
      // 所有被选中、叶子节点的key和半选中节点的key
      const keys = [
        ...this.$refs.rightsTreeRef.getCheckedKeys(),
        ...this.$refs.rightsTreeRef.getHalfCheckedKeys(),
      ];
      const idStr = keys.join(",");
      const {
        data: res
      } = await this.$request.post(
        `roles/${this.roleId}/rights`, {
          rids: idStr,
        }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("服务器错误，分配权限失败");
      }
      this.$message.success("分配权限成功");
      this.getRoleList();
      this.setRightsDialogVisiable = false;
    },
    // 点击添加角色按钮添加角色
    async addRole() {
      this.addForm.roleName = this.addForm.roleName.trim();
      this.roleList.forEach((item) => {
        if (item.roleName === this.addForm.roleName)
          return this.$message.error("该角色已存在请重新输入角色名称");
      });
      const {
        data: res
      } = await this.$request.post("roles", {
        roleName: this.addForm.roleName,
        roleDesc: this.addForm.roleDesc,
      });
      if (res.meta.status !== 201) {
        this.addRoleDialogVisiable = false;
        return this.$message.error("服务器错误，添加角色失败");
      }
      this.getRoleList();
      this.addRoleDialogVisiable = false;
    },
    // 监听添加角色对话框的关闭
    addRoletDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    // 点击编辑按钮，编辑角色描述
    async showEditDialog(row) {
      this.editDescDialogVisiable = true;
      const {
        data: res
      } = await this.$request(`roles/${row.id}`);
      if (res.meta.status !== 200) {
        this.addRoleDialogVisiable = false;
        return this.$message.error("服务器错误，获取角色失败");
      }
      this.editForm = res.data;
    },
    // 提交编辑角色描述
    async editDesc() {
      const {
        data: res
      } = await this.$request.put(
        `roles/${this.editForm.roleId}`, {
          roleName: this.editForm.roleName,
          roleDesc: this.editForm.roleDesc,
        }
      );
      if (res.meta.status !== 200) {
        this.addRoleDialogVisiable = false;
        return this.$message.error("服务器错误，编辑角色失败");
      }
      this.editDescDialogVisiable = false;
      this.getRoleList();
    },
    // 监听编辑对话框的关闭
    editDescDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },

    // 删除角色
    async deleteRole(row) {
      const result = await this.$confirm(
        "此操作将删除该角色, 是否继续?",
        "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (result !== 'confirm') return this.$message.info('取消删除')
      const {
        data: res
      } = await this.$request.delete(
        `roles/${row.id}`);
      if (res.meta.status !== 200) {
        this.addRoleDialogVisiable = false;
        return this.$message.error("服务器错误，编辑角色失败");
      }
      this.getRoleList()
    },
  },
};
</script>

<style lang="less" scoped>
.el-card {
  margin-top: 15px;
}

.el-table {
  margin-top: 15px;
}

.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}
</style>
